<template>
  <PageContainer
    title="发车订单详情"
    :description="`车辆：${vehicleInfo?.vehiclePlate || ''} - 司机：${
      vehicleInfo?.driverName || ''
    }`"
    :actions="pageActions"
    :columns="columns"
    :data-source="orderList"
    :loading="loading"
    :pagination-data="pagination"
    @search="handleSearch"
    @reset="handleReset"
    @pagination-change="handlePaginationChange"
  >
    <!-- 筛选条件 -->
    <template #filter-items>
      <a-form-item label="运单编号">
        <a-input
          v-model:value="queryParams.orderNo"
          placeholder="请输入运单编号"
          style="width: 180px"
          allowClear
        />
      </a-form-item>
      <a-form-item label="货物编码">
        <a-input
          v-model:value="queryParams.goodsCode"
          placeholder="请输入货物编码"
          style="width: 180px"
          allowClear
        />
      </a-form-item>
      <a-form-item label="客户姓名">
        <a-input
          v-model:value="queryParams.senderName"
          placeholder="请输入客户姓名"
          style="width: 150px"
          allowClear
        />
      </a-form-item>
      <a-form-item label="收货地址">
        <a-input
          v-model:value="queryParams.receiverAddress"
          placeholder="请输入收货地址"
          allowClear
        />
      </a-form-item>
      <a-form-item label="订单状态">
        <a-select
          v-model:value="queryParams.orderStatus"
          placeholder="全部状态"
          style="width: 150px"
          allowClear
          :options="statusOptions"
        />
      </a-form-item>
      <a-form-item label="装车时间">
        <a-range-picker
          v-model:value="loadedTimeRange"
          format="YYYY-MM-DD"
          :placeholder="['开始日期', '结束日期']"
          style="width: 200px"
        />
      </a-form-item>
    </template>

    <!-- 使用新的 bodyCell 插槽语法 -->
    <template #bodyCell="{ column, record }">
      <!-- 运单编号列 -->
      <template v-if="column.key === 'orderNo'">
        <div class="order-info">
          <div class="order-no">{{ record.orderNo }}</div>
          <div class="order-meta">{{ record.goodsCode }}</div>
        </div>
      </template>

      <!-- 发货信息列 -->
      <template v-else-if="column.key === 'senderInfo'">
        <div class="sender-info">
          <div>
            <strong>{{ record.senderName }}</strong>
          </div>
          <div class="phone">{{ record.senderPhone }}</div>
        </div>
      </template>

      <!-- 收货信息列 -->
      <template v-else-if="column.key === 'receiverInfo'">
        <div class="receiver-info">
          <div>
            <strong>{{ record.receiverName }}</strong>
          </div>
          <div class="phone">{{ record.receiverPhone }}</div>
          <div class="address">{{ record.receiverAddress }}</div>
        </div>
      </template>

      <!-- 站点路线列 -->
      <template v-else-if="column.key === 'siteRoute'">
        <div class="site-route">
          <span>{{ record.departureSiteName }}</span>
          <ArrowRightOutlined class="site-arrow" />
          <span>{{ record.arrivalSiteName }}</span>
        </div>
      </template>

      <!-- 状态列 -->
      <template v-else-if="column.key === 'orderStatus'">
        <a-tag :color="getStatusMeta(record.orderStatus)?.color">
          {{ getStatusMeta(record.orderStatus)?.label }}
        </a-tag>
      </template>

      <!-- 装车时间列 -->
      <template v-else-if="column.key === 'loadedAt'">
        <span v-if="record.loadedAt">{{
          formatDateTime(record.loadedAt)
        }}</span>
        <span v-else class="text-secondary">未装车</span>
      </template>

      <!-- 发车时间列 -->
      <template v-else-if="column.key === 'dispatchedAt'">
        <span v-if="record.dispatchedAt">{{
          formatDateTime(record.dispatchedAt)
        }}</span>
        <span v-else class="text-secondary">未发车</span>
      </template>

      <!-- 操作列 -->
      <template v-else-if="column.key === 'action'">
        <a-space>
          <a-button
            v-if="record.orderStatus === 'LOADED'"
            type="link"
            size="small"
            @click="handleUnload(record)"
            v-permission="'order:unload'"
          >
            卸车
          </a-button>
          <a-button
            v-if="record.orderStatus === 'TRANSPORTING'"
            type="link"
            size="small"
            @click="handleArrive(record)"
            v-permission="'order:arrive'"
          >
            标记到达
          </a-button>
          <a-button type="link" size="small" @click="handleViewDetail(record)">
            详情
          </a-button>
        </a-space>
      </template>
    </template>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { ArrowRightOutlined } from "@ant-design/icons-vue";
import type { Dayjs } from "dayjs";
import PageContainer from "@/components/business/PageContainer.vue";
import { getOrderList, orderUnload } from "@/api/tenant/order";
import { formatDateTime } from "@/utils/date";

// 订单状态配置
const ORDER_STATUS_CONFIG = {
  RECEIVED: { label: "已接单", color: "blue" },
  LOADED: { label: "已装车", color: "orange" },
  TRANSPORTING: { label: "运输中", color: "cyan" },
  ARRIVED: { label: "已到达", color: "purple" },
  DELIVERING: { label: "配送中", color: "geekblue" },
  COMPLETED: { label: "已完成", color: "green" },
};

type OrderStatus = keyof typeof ORDER_STATUS_CONFIG;

const route = useRoute();
const router = useRouter();

// 车辆信息
const vehicleInfo = ref<{
  vehicleId: number;
  vehiclePlate: string;
  driverId: number;
  driverName: string;
  driverPhone: string;
}>();

// 查询参数
const queryParams = reactive({
  vehicleId: undefined as number | undefined,
  orderNo: "",
  goodsCode: "",
  senderName: "",
  receiverAddress: "",
  orderStatus: undefined as OrderStatus | undefined,
});

const loadedTimeRange = ref<[Dayjs, Dayjs] | null>(null);
const loading = ref(false);
const orderList = ref<any[]>([]);

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
});

// 状态选项
const statusOptions = Object.entries(ORDER_STATUS_CONFIG).map(
  ([value, meta]) => ({
    label: meta.label,
    value: value as OrderStatus,
  })
);

const getStatusMeta = (status?: OrderStatus) =>
  status ? ORDER_STATUS_CONFIG[status] : undefined;

// 页面操作按钮
const pageActions = computed(() => [
  {
    key: "back",
    label: "返回",
    onClick: () => router.back(),
  },
  {
    key: "refresh",
    label: "刷新",
    onClick: () => fetchOrderList(),
  },
]);

// 表格列定义
const columns = [
  { title: "运单信息", key: "orderNo", width: 140 },
  { title: "发货人", key: "senderInfo", width: 120 },
  { title: "收货人", key: "receiverInfo", width: 180 },
  { title: "站点路线", key: "siteRoute", width: 160 },
  { title: "订单状态", key: "orderStatus", width: 100 },
  { title: "装车时间", key: "loadedAt", width: 150 },
  { title: "发车时间", key: "dispatchedAt", width: 150 },
  { title: "操作", key: "action", width: 150, fixed: "right" as const },
];

// 获取订单列表
const fetchOrderList = async () => {
  try {
    loading.value = true;

    const params: any = {
      ...queryParams,
      current: pagination.current,
      size: pagination.pageSize,
    };

    // 时间范围
    if (loadedTimeRange.value && loadedTimeRange.value.length === 2) {
      params.loadedAtStart = loadedTimeRange.value[0].format(
        "YYYY-MM-DD 00:00:00"
      );
      params.loadedAtEnd = loadedTimeRange.value[1].format(
        "YYYY-MM-DD 23:59:59"
      );
    }

    const res = await getOrderList(params);
    const data = res.data as any;
    orderList.value = data?.records ?? [];
    pagination.total = data?.total ?? 0;
  } catch (error: any) {
    message.error(error.message || "获取订单列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  fetchOrderList();
};

// 重置处理
const handleReset = () => {
  Object.assign(queryParams, {
    orderNo: "",
    goodsCode: "",
    senderName: "",
    receiverAddress: "",
    orderStatus: undefined,
  });
  loadedTimeRange.value = null;
  pagination.current = 1;
  fetchOrderList();
};

// 分页处理
const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  fetchOrderList();
};

// 卸车操作
const handleUnload = async (record: any) => {
  try {
    await orderUnload({ ids: [record.id] });
    message.success("卸车成功");
    fetchOrderList();
  } catch (error: any) {
    message.error(error.message || "卸车失败");
  }
};

// 标记到达操作
const handleArrive = async (record: any) => {
  try {
    // TODO: 调用标记到达API
    message.success("已标记到达");
    fetchOrderList();
  } catch (error: any) {
    message.error(error.message || "标记到达失败");
  }
};

// 查看详情
const handleViewDetail = (record: any) => {
  router.push(`/tenant/order/${record.id}`);
};

// 组件初始化
onMounted(() => {
  const vehicleId = Number(route.params.vehicleId);
  const vehiclePlate = route.query.vehiclePlate as string;
  const driverName = route.query.driverName as string;
  const driverPhone = route.query.driverPhone as string;

  if (!vehicleId || !vehiclePlate) {
    message.error("车辆信息不完整");
    router.back();
    return;
  }

  vehicleInfo.value = {
    vehicleId,
    vehiclePlate,
    driverId: Number(route.query.driverId) || 0,
    driverName: driverName || "",
    driverPhone: driverPhone || "",
  };

  queryParams.vehicleId = vehicleId;
  fetchOrderList();
});
</script>

<style scoped>
.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-no {
  font-weight: 600;
  color: var(--primary-color);
}

.order-meta {
  font-size: 12px;
  color: var(--text-secondary);
}

.sender-info,
.receiver-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.phone {
  font-size: 12px;
  color: var(--text-secondary);
}

.address {
  font-size: 12px;
  color: var(--text-secondary);
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.site-route {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-primary);
}

.site-arrow {
  color: var(--text-secondary);
}

.text-secondary {
  color: var(--text-secondary);
}
</style>
